<template>
    <div class="page-maneger-add">
    <el-form label-width="60px" ref="formRef" :model="formData" :rules="formRules">
      <el-form-item label="账号" prop="adminname">
        <el-input v-model="formData.adminname" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password"/>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="formData.role">
              <el-option value="2" label="超级管理员"/>
              <el-option value="1" label="管理员"/>
        </el-select>
      </el-form-item>
      <el-form-item label="权限" prop="checkedKeys" width="100px">
            <!-- tree的勾选数据，需要通过方法去主动获取，不能v-model双向绑定 -->
            <el-tree 
            :data="treeData" 
            :props="defaultProps"
            show-checkbox 
            ref="treeRef"
            node-key="name"
            default-expand-all
            />
          </el-form-item>
      <el-form-item label="操作">
        <el-button @click="handleAdd" >添加</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>export default{name:"maneger/add"}</script>

<script setup>
import { onMounted, reactive,ref } from 'vue';
import {addManegerList} from "../../api/maneger"
import { useRouter } from 'vue-router';
import {routes} from "../../router/index"

const formRef=ref()
const treeRef=ref()
const router=useRouter()
const formData=reactive({
        adminname: "",
        password: "",
        role: "",
        //勾选的路由的名字
        checkedKeys: [],
      })
      //表单校验
const formRules=reactive({
        adminname:[{required:true,message:"请填写"}],
        password:[{required:true,message:"请填写"}],
        role:[{required:true,message:"请填写"}],
        checkedKeys:[{required:true,message:"请填写"}],
      })
      
const treeData=ref ([])
const defaultProps={
        //每一个节点的子节点是什么字段，默认值就是children
        children: "children",
        //label就是每一个节点用来展示文案的字段,默认值就是label
        label: "lable",
      }


      //权限treeData
      onMounted(()=>{
        //console.log(routes);
        treeData.value=routes.filter((item)=>{
            return !item.hidden
        })
      })

const handleAdd=async()=>{
    try {
        
        const list1=treeRef.value.getCheckedKeys()
        const list2=treeRef.value.getHalfCheckedKeys()
        /* console.log(list1);
        console.log(list2); */
        formData.checkedKeys=[...list1,...list2]
       await  formRef.value.validate()

       addManegerList(formData).then((res)=>{
        console.log(res);
        if(res==undefined){
          alert("该账号已存在，请重新设置")
        }
       })

    } catch (error) {
        console.log(err);
    }
    
}



</script>

<style scoped>
.el-form{
}
.el-form-item{
  margin-bottom: 30px;
}
</style>